import { json, type LoaderFunctionArgs } from "@remix-run/node";

function computeAppUrl(): string {
  const raw = process.env.SHOPIFY_APP_URL || "";
  if (!raw) return "";
  return raw.startsWith("http") ? raw : `https://${raw}`;
}

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const shop = url.searchParams.get("shop");
  const state = url.searchParams.get("state") || "";
  const redirectParam = url.searchParams.get("redirectUri");
  const forward = url.searchParams.get("forward");
  const method = url.searchParams.get("method");

  if (!shop) {
    return json({ success: false, error: "Missing shop" }, { status: 400 });
  }

  const clientId = process.env.SHOPIFY_API_KEY;
  const scopes = process.env.SCOPES || "";
  const appUrl = computeAppUrl();
  let redirectUri = redirectParam || (appUrl ? `${appUrl}/auth/capture` : "");

  // If forwarding specified, attach as query to capture route so it can forward the code externally
  if (!redirectParam && redirectUri && (forward || method)) {
    const r = new URL(redirectUri);
    if (forward) r.searchParams.set('forward', forward);
    if (method) r.searchParams.set('method', method);
    redirectUri = r.toString();
  }

  if (!clientId || !redirectUri) {
    return json({ success: false, error: "App not configured: API_KEY or APP_URL/redirectUri missing" }, { status: 500 });
  }

  const params = new URLSearchParams({
    client_id: clientId,
    scope: scopes,
    redirect_uri: redirectUri,
    state,
  });

  // You can append grant_options[]=per-user if you need online access mode
  const authorizeUrl = `https://${shop}/admin/oauth/authorize?${params.toString()}`;

  return json({ success: true, authorizeUrl, redirectUri });
};


